package com.ficus.road.maintain.authority.handler;

import com.alibaba.fastjson.JSONObject;
import com.ficus.road.maintain.authority.config.AuthorityConfig;
import com.ficus.road.maintain.authority.service.RoleService;
import com.ficus.road.maintain.authority.service.UserService;
import com.ficus.road.maintain.authority.vo.LoginErrorResponse;
import com.ficus.road.maintain.authority.vo.LoginResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author xiawen yang
 * 自定义认证成功处理器
 * @date 2021/8/27 上午11:00
 */
@Component("myAuthenticationSuccessHandler")
@Slf4j
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private AuthorityConfig authorityConfig;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        request.getSession().setMaxInactiveInterval(authorityConfig.getTtl().intValue());
        String username = ((User) authentication.getPrincipal()).getUsername();
        LoginResponse loginResponse = userService.queryLoginInfoByUsername(username);
        //账户在锁定状态下
        if (loginResponse.getErrorsNumber() == -1){
            LoginErrorResponse loginErrorResponse = new LoginErrorResponse();
            loginErrorResponse.setLockTime(loginResponse.getLockTime());
            loginErrorResponse.setErrorsNumber(-1);
            loginErrorResponse.setMessage("账户已锁定");
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(JSONObject.toJSONString(loginErrorResponse));
            //账户未在锁定状态下
        }else {
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(JSONObject.toJSONString(loginResponse));
            log.info("user : {}, login success", username);
        }
    }
}
